<!--
 * @Description:
 * @version:
 * @Author: 尹鹏孝
 * @Date: 2023-03-30 09:02:22
 * @LastEditors: 尹鹏孝
 * @LastEditTime: 2023-03-30 10:31:02
-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>6种继承及其优缺点</title>
</head>
<body>
<script>

// 1、原型链继承
function SuperType(){
    this.prototype=true;
}

SuperType.prototype.getSuperValue = function(){
    return this.prototype;
}
function SubType(){
    this.subProperty=false;
}

SubType.prototype = new SuperType()
SubType.prototype.getSubValue = function(){
    return this.subProperty;
}
var instance = new SubType();
//alert(instance.getSuperValue());
//实例共享，修改则会波及其他。不能将参数传递给父级

//借用构造函数
function SuperType(name){
    this.name = name;
}

function SUbType(){
    SuperType.call(this,'shelley')
    this.age=20;
}

var instance = new SubType();

// 优点:可以在类型构造函数中间向超类构造函数传参
// 缺点：方法都定义在构造函数中，及定义了很多功能，函数复用无从谈起


// 使用组合原型链和构造函数
function SuperType(name){
    this.name=name;
    this.color=['red','blue','green']
}
SuperType.prototype.sayName=function(){
    console.log(this.name)
}

function SubType(age,name){
    SuperType.call(this,name)
    this.age=age;
}

SubType.prototype=new SuperType();
SubType.prototype.constructor=SubType;
SubType.prototype.sayName = function(){
    console.log(this.age);
}

// 缺点：无论什么情况下，都会调用两次超类型构造函数，一次是在创建子类型原型的时候，一次是在子类型构造函数内部
// 原型式继承

function object(o){
    function F(){
        F.prototype=o;
    }
    return new F();
}

//对象的浅复制，与Object.create行为相同
// 寄生式继承
function createAnother(o){
    var clone = object(o);
    clone.sayHi = function(){
        console.log('hi,hi')
    }
    return clone;
}
//与构造函数模式类似，不能做导函数复用，降低了效率

// 寄生组合式继承

========================
function object(o) {
    function F() {
        F.prototype = o;
    }
    return new F();
}
======================
function inheritPrototype(subType,superType){
    var prototype = object(superType.prototype)
    prototype.constructor = subType;
    subType.prototype=prototype;
}
=======================
function SuperType(name){
    this.name = name;
    this.color = ['red','blue','green']
}
SuperType.prototype.sayName = function(){
    console.log(this.name);
}
function SubType(name,age){
    SuperType.call(this,name);
    this.age=age;
}
=======================

inheritPrototype(SubType,SuperType)
// 优点：解决了组合使用原型链和构造函数继承两次调用超类型构造函数的缺点,比较复杂的方式


</script>
</body>
</html>